<template>
  <div class="simple-carousel">
    <div v-if="banners.length > 0" class="carousel-container">
      <!-- 轮播图主体 -->
      <div class="carousel-wrapper" @mouseenter="pauseAutoplay" @mouseleave="resumeAutoplay">
        <div 
          class="carousel-track" 
          :style="{ transform: `translateX(-${currentIndex * 100}%)` }"
        >
          <div 
            v-for="(banner, index) in banners" 
            :key="banner.id"
            class="carousel-slide"
            @click="handleBannerClick(banner)"
          >
            <img 
              :src="getFullImageUrl(banner.imageUrl)"
              :alt="banner.title"
              class="carousel-image"
              @error="(e) => handleImageError(e, 'banner')"
            />
            <div class="carousel-overlay">
              <div class="carousel-content">
                <h2 class="carousel-title">{{ banner.title }}</h2>
                <p v-if="banner.description" class="carousel-description">
                  {{ banner.description }}
                </p>
                <div v-if="banner.linkUrl || (banner.targetType && banner.targetId)" class="carousel-action">
                  <el-button type="primary" size="large" round>
                    了解更多
                    <el-icon><ArrowRight /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 导航按钮 -->
      <div v-if="banners.length > 1" class="carousel-navigation">
        <button 
          class="nav-btn prev-btn" 
          @click="prevSlide"
          :disabled="currentIndex === 0 && !loop"
        >
          <el-icon><ArrowLeft /></el-icon>
        </button>
        <button 
          class="nav-btn next-btn" 
          @click="nextSlide"
          :disabled="currentIndex === banners.length - 1 && !loop"
        >
          <el-icon><ArrowRight /></el-icon>
        </button>
      </div>
      
      <!-- 指示器 -->
      <div v-if="banners.length > 1" class="carousel-indicators">
        <button
          v-for="(banner, index) in banners"
          :key="index"
          class="indicator"
          :class="{ active: index === currentIndex }"
          @click="goToSlide(index)"
        ></button>
      </div>
    </div>
    
    <!-- 无数据时的占位内容 -->
    <div v-else-if="!loading" class="carousel-placeholder">
      <div class="placeholder-content">
        <el-icon class="placeholder-icon"><Picture /></el-icon>
        <h3>暂无轮播图</h3>
        <p>管理员还未添加轮播图内容</p>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="carousel-loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight, Picture, Loading } from '@element-plus/icons-vue'
import { carouselApi, type CarouselBanner } from '@/api/carousel'
import { getFullImageUrl, handleImageError, preloadImages } from '@/utils/imageUtils'

const router = useRouter()

// 响应式数据
const banners = ref<CarouselBanner[]>([])
const loading = ref(true)
const currentIndex = ref(0)
const autoplayTimer = ref<number | null>(null)
const loop = ref(true)
const autoplayDelay = ref(4000)

// 获取轮播图数据
const fetchCarouselBanners = async () => {
  try {
    loading.value = true
    console.log('开始获取轮播图数据...')
    
    const response = await carouselApi.getCarouselList()
    console.log('轮播图API响应:', response)
    
    const allBanners = response.data || []
    const validBanners = allBanners.filter((banner: CarouselBanner) => banner.status === 1)
    
    console.log(`获取到轮播图: ${allBanners.length} 个，有效的: ${validBanners.length} 个`)
    
    banners.value = validBanners
    
    // 预加载图片
    if (validBanners.length > 0) {
      const imageUrls = validBanners.map(banner => getFullImageUrl(banner.imageUrl)).filter(Boolean)
      preloadImages(imageUrls).then(results => {
        const failedCount = results.filter(success => !success).length
        if (failedCount > 0) {
          console.warn(`${failedCount} 张轮播图图片加载失败`)
        }
      })
      
      // 启动自动播放
      if (validBanners.length > 1) {
        startAutoplay()
      }
    }
  } catch (error) {
    console.error('获取轮播图失败:', error)
    ElMessage.error('获取轮播图数据失败')
  } finally {
    loading.value = false
  }
}

// 切换到上一张
const prevSlide = () => {
  if (banners.value.length <= 1) return
  
  if (currentIndex.value > 0) {
    currentIndex.value--
  } else if (loop.value) {
    currentIndex.value = banners.value.length - 1
  }
  
  console.log('切换到上一张:', currentIndex.value)
}

// 切换到下一张
const nextSlide = () => {
  if (banners.value.length <= 1) return
  
  if (currentIndex.value < banners.value.length - 1) {
    currentIndex.value++
  } else if (loop.value) {
    currentIndex.value = 0
  }
  
  console.log('切换到下一张:', currentIndex.value)
}

// 跳转到指定幻灯片
const goToSlide = (index: number) => {
  if (index >= 0 && index < banners.value.length) {
    currentIndex.value = index
    console.log('跳转到幻灯片:', index)
  }
}

// 启动自动播放
const startAutoplay = () => {
  if (banners.value.length <= 1) return
  
  stopAutoplay()
  autoplayTimer.value = window.setInterval(() => {
    nextSlide()
  }, autoplayDelay.value)
  
  console.log('自动播放已启动')
}

// 停止自动播放
const stopAutoplay = () => {
  if (autoplayTimer.value) {
    clearInterval(autoplayTimer.value)
    autoplayTimer.value = null
  }
}

// 暂停自动播放
const pauseAutoplay = () => {
  stopAutoplay()
  console.log('自动播放已暂停')
}

// 恢复自动播放
const resumeAutoplay = () => {
  if (banners.value.length > 1) {
    startAutoplay()
    console.log('自动播放已恢复')
  }
}

// 处理轮播图点击
const handleBannerClick = (banner: CarouselBanner) => {
  if (banner.linkType === 1) return // 无链接
  
  if (banner.linkType === 2 && banner.targetType && banner.targetId) {
    // 内部链接
    const routes: Record<string, string> = {
      culture: `/culture/${banner.targetId}`,
      tutorial: `/tutorial/${banner.targetId}`,
      news: `/news/${banner.targetId}`
    }
    
    if (routes[banner.targetType]) {
      router.push(routes[banner.targetType])
    }
  } else if (banner.linkType === 3 && banner.linkUrl) {
    // 外部链接
    window.open(banner.linkUrl, '_blank')
  }
}

// 组件挂载和卸载
onMounted(() => {
  fetchCarouselBanners()
})

onUnmounted(() => {
  stopAutoplay()
})

// 暴露给父组件的方法
defineExpose({
  refresh: fetchCarouselBanners,
  prevSlide,
  nextSlide,
  goToSlide
})
</script>

<style scoped>
.simple-carousel {
  width: 100%;
  height: 400px;
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.carousel-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.carousel-wrapper {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.carousel-track {
  display: flex;
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease-in-out;
}

.carousel-slide {
  flex: 0 0 100%;
  height: 100%;
  position: relative;
  cursor: pointer;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

.carousel-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.4) 0%,
    rgba(0, 0, 0, 0.2) 50%,
    rgba(0, 0, 0, 0.4) 100%
  );
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.carousel-content {
  text-align: center;
  color: #fff;
  max-width: 700px;
  animation: fadeInUp 0.8s ease-out;
}

.carousel-title {
  font-size: 42px;
  font-weight: bold;
  margin-bottom: 16px;
  text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.5);
  line-height: 1.2;
}

.carousel-description {
  font-size: 18px;
  margin-bottom: 24px;
  text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.5);
  line-height: 1.5;
  opacity: 0.95;
}

.carousel-action {
  margin-top: 20px;
}

.carousel-action .el-button {
  font-size: 16px;
  padding: 12px 32px;
  background: linear-gradient(135deg, #d32f2f, #f57c00);
  border: none;
  box-shadow: 0 4px 15px rgba(211, 47, 47, 0.3);
  transition: all 0.3s ease;
}

.carousel-action .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(211, 47, 47, 0.4);
}

/* 导航按钮 */
.carousel-navigation {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  pointer-events: none;
}

.nav-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.3);
  border: none;
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  pointer-events: auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-btn:hover:not(:disabled) {
  background: rgba(0, 0, 0, 0.5);
  transform: scale(1.1);
}

.nav-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

/* 指示器 */
.carousel-indicators {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 12px;
}

.indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.indicator.active {
  background: #fff;
  transform: scale(1.2);
}

.indicator:hover {
  background: rgba(255, 255, 255, 0.8);
}

/* 占位和加载状态 */
.carousel-placeholder,
.carousel-loading {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  color: #666;
}

.placeholder-content,
.carousel-loading {
  text-align: center;
}

.placeholder-icon,
.loading-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.loading-icon {
  animation: rotate 2s linear infinite;
}

.carousel-placeholder h3,
.carousel-loading p {
  margin: 8px 0;
  color: #666;
}

.carousel-placeholder p {
  color: #999;
  font-size: 14px;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .simple-carousel {
    height: 300px;
  }

  .carousel-placeholder,
  .carousel-loading {
    height: 300px;
  }

  .carousel-title {
    font-size: 28px;
  }

  .carousel-description {
    font-size: 16px;
  }

  .carousel-action .el-button {
    font-size: 14px;
    padding: 10px 24px;
  }

  .nav-btn {
    width: 40px;
    height: 40px;
  }
}

@media (max-width: 480px) {
  .simple-carousel {
    height: 250px;
    border-radius: 8px;
  }

  .carousel-placeholder,
  .carousel-loading {
    height: 250px;
    border-radius: 8px;
  }

  .carousel-overlay {
    padding: 20px 15px;
  }

  .carousel-title {
    font-size: 24px;
    margin-bottom: 12px;
  }

  .carousel-description {
    font-size: 14px;
    margin-bottom: 20px;
  }

  .carousel-action .el-button {
    font-size: 13px;
    padding: 8px 20px;
  }
}
</style>
